package com.lenovo.spider.process.exceptions;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Chain;

import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

/**
 * @author <a href="mailto:liuhan3@lenovo.com">HanL(liuhan3)</a>
 * on 2018/3/27 15:09
 */
public class ChainExceptionHandler extends ExceptionHandler implements Chain<ExceptionHandler, ChainExceptionHandler> {
    List<ExceptionHandler> chain;

    public ChainExceptionHandler(ExceptionHandler... handlers) {
        this.chain = CollUtil.newArrayList(handlers);
    }

    /**
     * 支持处理所有运行时异常
     *
     * @param throwable
     * @return
     */
    @Override
    boolean support(Throwable throwable) {
        return throwable instanceof RuntimeException;
    }

    @Override
    boolean handle(Throwable throwable) {
        CollUtil.sort(this.chain, Comparator.comparingInt(ExceptionHandler::getOrder));
        for (ExceptionHandler handler : this.chain) {
            if (handler.support(throwable) && handler.handle(throwable)) {
                break;
            }
        }
        return true;
    }

    @Override
    int getOrder() {
        return 0;
    }

    @Override
    public ChainExceptionHandler addChain(ExceptionHandler exceptionHandler) {
        this.chain.add(exceptionHandler);
        return this;
    }

    /**
     * Returns an iterator over elements of type {@code T}.
     *
     * @return an Iterator.
     */
    @Override
    public Iterator<ExceptionHandler> iterator() {
        return this.chain.iterator();
    }
}
